package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/CourseListServlet")
public class CourseListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        if (teacherId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        response.setContentType("application/json;charset=UTF-8");

        try {
            Connectmysql conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                String sql = "SELECT DISTINCT c.course_id, c.course_name " +
                        "FROM teaching t " +
                        "JOIN course c ON t.course_id = c.course_id " +
                        "WHERE t.teacher_id = ? AND t.status = 1";

                ResultSet rs = conn.executeSql(sql, new Object[]{teacherId});
                List<Map<String, Object>> courses = new ArrayList<>();

                while (rs.next()) {
                    Map<String, Object> course = new HashMap<>();
                    course.put("course_id", rs.getInt("course_id"));
                    course.put("course_name", rs.getString("course_name"));
                    courses.add(course);
                }

                response.getWriter().print(mapListToJson(courses));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("{\"error\": \"课程列表获取失败: " + e.getMessage() + "\"}");
        }
    }

    private String mapListToJson(List<Map<String, Object>> list) {
        StringBuilder json = new StringBuilder("[");
        boolean firstItem = true;

        for (Map<String, Object> item : list) {
            if (!firstItem) {
                json.append(",");
            }
            firstItem = false;

            json.append("{");
            boolean firstEntry = true;

            for (Map.Entry<String, Object> entry : item.entrySet()) {
                if (!firstEntry) {
                    json.append(",");
                }
                firstEntry = false;

                json.append("\"")
                        .append(escapeJson(entry.getKey()))
                        .append("\":");

                Object value = entry.getValue();
                if (value instanceof String) {
                    json.append("\"")
                            .append(escapeJson((String) value))
                            .append("\"");
                } else {
                    json.append(value);
                }
            }

            json.append("}");
        }

        json.append("]");
        return json.toString();
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}